package org.lsda.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lsda.util.Util;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

/**
 * Servlet implementation class ListProgram
 */
@WebServlet("/ListProgram")
public class ListProgram extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ListProgram() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		
		ArrayList<String> programs = null;
		Connection conn = null;
		JsonObject json = new JsonObject();
		json.addProperty("Result", "OK");
		try {
			conn = Util.getConnection();
			programs = Util.listProgram(conn);
		} catch (Exception ex) {
			json.addProperty("Result", "ERROR");
			json.addProperty("Message", ex.getMessage());
		} finally {
			try {
				conn.close();
			} catch (Exception ignore) {
			}

		}

		JsonArray records = new JsonArray();
		for (String p : programs) {
			JsonObject prog = new JsonObject();
			prog.addProperty("DisplayText", p);
			prog.addProperty("Value", p);
			records.add(prog);
		}

		json.add("Options", records);

		PrintWriter writer = response.getWriter();
//		System.out.println(json.toString());
		writer.write(json.toString());

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
